﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Kiiro.Common.Entities;
using Kiiro.Common.Interfaces;
using Kiiro.Common.Utility;
using Kiiro.SiteDefinition.ControlTemplates;
using Kiiro.Model;
using Kiiro.SiteDefinition.Core;
using Kiiro.SiteDefinition.MasterPage;
using Microsoft.SharePoint.Utilities;

namespace Kiiro.SiteDefinition.ProjectPages
{
    public partial class EditTeamMember : BasePage
    {
        #region Properties
        public TeamMember TeamMember
        {
            get;
            set;
        }

        public Project CurrentProject
        {
            get;
            set;
        }

        public CustomFieldCollection CustomFields
        {
            get { return ( CustomFieldCollection ) v2CustomFieldCollection; }
        }

        public NavigationSub NavigationSub
        {
            get { return KiiroMaster.NavigationSub; }
        }

        public FormButtons Buttons
        {
            get { return ( FormButtons ) v2FormButtons; }
        }
        #endregion

        #region Page Events
        protected override void OnInit ( EventArgs e )
        {
            base.OnInit ( e );
            CustomFields.ControlMode = SPControlMode.Edit;
            NavigationSub.DeleteButton.ControlMode = SPControlMode.Edit;
            Buttons.SaveButton.ControlMode = SPControlMode.Edit;
            Buttons.CancelButton.ControlMode = SPControlMode.Edit;
        }

        protected void Page_Load ( object sender, EventArgs e )
        {
            CustomFields.EntityType = typeof ( TeamMember );
            CustomFields.Title = "Additional Information";

            SPContext context = CustomModel.GetCustomFieldsContext ( typeof ( TeamMember ), ItemId, Context, SiteCollectionId, ServerRelativeUrl );
            context.FormContext.FormMode = SPControlMode.Edit;

            Buttons.SaveButton.ItemId = ItemId;
            Buttons.SaveButton.ItemContext = context;
            Buttons.SaveButton.RenderContext = context;

            Buttons.CancelButton.ItemContext = context;
            Buttons.CancelButton.RenderContext = context;
            Buttons.CancelButton.RedirectUrl = Cancel ( );

            NavigationSub.DeleteButton.ItemContext = context;
            NavigationSub.DeleteButton.RenderContext = context;

            litTitle.Text = "Edit Team Member";

            if ( KiiroMaster.V2Header.Project != null && !string.IsNullOrEmpty ( KiiroMaster.V2Header.Project.Title ) )
            {
                litTitle.Text = KiiroMaster.V2Header.Project.Title + " - Edit Team Member";
            }

            TeamMember = TeamModel.GetTeamMembersById ( ItemId, SiteCollectionId, ServerRelativeUrl );

            CurrentProject = ProjectsModel.GetByServerRelativeWebUrl(SiteCollectionId, ServerRelativeUrl);

            if ( TeamMember != null )
            {
                bool canEdit = PermissionsModel.CanTeamMemberUpdateThemselves ( CurrentUser, TeamMember, SiteCollectionId, ServerRelativeUrl );

                if ( canEdit )
                {
                    litTitle.Text = litTitle.Text + " - " + TeamMember.User.FullName;

                    AddCommandButtons ( );

                    if ( !Page.IsPostBack )
                        PopulateForm ( );
                }
                else
                {
                    Response.Redirect ( Cancel ( ) );
                }
            }
        }
        #endregion

        internal override string Cancel ( )
        {
            return ServerRelativeUrl + Constants.ProjectFileUrls.Team;
        }

        internal override bool Save ( )
        {
            bool canEdit = PermissionsModel.CanTeamMemberUpdateThemselves ( CurrentUser, TeamMember, SiteCollectionId, ServerRelativeUrl );

            if ( canEdit )
            {
                TeamMember.ClearValidationMessages ( );

                TeamMember.CreatedBy = CurrentUser;
                TeamMember.CreatedDate = DateTime.Now;

                TeamMember.IsProjectManager = chkIsProjectManager.Checked;
                TeamMember.RoleOnProject = txtRoleOnProject.Text;
                TeamMember.UserId = TeamMember.User.Id;

                TeamMember.ServerRelativeUrl = ServerRelativeUrl;
                TeamMember.SiteCollectionId = SiteCollectionId;
                TeamMember.ModifiedBy = CurrentUser;
                TeamMember.ModifiedDate = DateTime.Now;
                TeamMember.CustomFieldNamesAndValues = CustomFields.HarvestCustomFieldValues ( );

                TeamMember.EditType = EditType.Updated;

                TeamMember = TeamModel.Save ( TeamMember, SiteCollectionId, ServerRelativeUrl );

                if ( TeamMember.IsValid ( ) )
                    Response.Redirect ( Cancel ( ) );
                else
                    PopulateErrorMessages ( );
            }
            else
            {
                Response.Redirect ( Cancel ( ) );
            }
            return true;
        }

        internal override void Delete ( )
        {
            if ( PermissionBitsTeams [ 3 ] )
            {
                TeamMember.EditType = EditType.Deleted;
                TeamMember.ModifiedBy = CurrentUser;
                TeamMember.ServerRelativeUrl = ServerRelativeUrl;

                TeamMember = TeamModel.Save ( TeamMember, SiteCollectionId, ServerRelativeUrl );
            }

            if ( TeamMember.IsValid ( ) )
                Response.Redirect ( Cancel ( ) );
            else
            {
                KiiroMaster.V2ErrorsList.ErrorMessages.Add ( FormattingHelpers.GetErrorMessageText ( TeamMember.IsProjectManagerMessage ) );
                KiiroMaster.V2ErrorsList.ErrorMessages.Add ( FormattingHelpers.GetErrorMessageText ( TeamMember.EditTypeMessage ) );
            }
        }

        private void AddCommandButtons ( )
        {
            if ( PermissionBitsTeams [ 3 ] )
            {
                List<LinkButton> buttons = new List<LinkButton> ( );

                LinkButton btnDelete = new LinkButton ( );
                btnDelete.Text = "Delete this Team Member";
                btnDelete.Attributes.Add ( "class", "icon-delete" );
                string js = "javascript:{0}__doPostBack('ctl00$MainContent$V2NavigationSub$diidIODeleteItem','')";
                btnDelete.OnClientClick = string.Format ( js, "if (confirm('Are you sure that you want to delete this team member?'))" );
                NavigationSub.Commands.Add ( btnDelete );
            }
        }

        private void PopulateForm ( )
        {
            if ( TeamMember.User != null )
            {
                lnkFullName.NavigateUrl = String.Format ( "{0}{1}?id={2}", ServerRelativeUrl, Constants.PortalFileUrls.UserDisplay, TeamMember.User.SPUserId );
                lnkFullName.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( TeamMember.User.FullName );
                lblPhoneNumber.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( TeamMember.User.PhoneNumber );
                lblEmail.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( TeamMember.User.Email );
                lblIM.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( TeamMember.User.IM );
                lblStatusNote.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( TeamMember.User.StatusNote );
                imgPicture.ImageUrl = TeamMember.User.PictureUrl ?? "/_layouts/images/Kiiro/person-thumb.gif";

                txtRoleOnProject.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( TeamMember.RoleOnProject );
                chkIsProjectManager.Checked = TeamMember.IsProjectManager;


                chkIsProjectManager.Enabled = false;

                if ( CurrentUser.IsAdministrator  || CurrentProject.ProjectManagerIds.Exists( x => x == CurrentUser.UserId ) )
                {
                    chkIsProjectManager.Enabled = TeamMember.User.Id != CurrentUser.Id || CurrentUser.IsAdministrator;
                }

                PopulateErrorMessages ( );
            }
            else
            {
                Response.Redirect ( Cancel ( ) );
            }
        }

        private void PopulateErrorMessages ( )
        {
            lblRoleOnProjectMessage.Text = FormattingHelpers.GetErrorMessageText ( TeamMember.RoleOnProjectMessage );
            lblRoleOnProjectMessage.Visible = !string.IsNullOrEmpty ( lblRoleOnProjectMessage.Text );
            lblRoleOnProjectMessage.Text = FormattingHelpers.GetErrorMessageText ( TeamMember.RoleOnProjectMessage );
            lblRoleOnProjectMessage.Visible = !string.IsNullOrEmpty ( lblRoleOnProjectMessage.Text );
            lblIsProjectManagerMessage.Text = FormattingHelpers.GetErrorMessageText ( TeamMember.IsProjectManagerMessage );
            lblIsProjectManagerMessage.Visible = !string.IsNullOrEmpty ( lblIsProjectManagerMessage.Text );
        }
    }
}

/*************************************************************************
 * 
 * $Log: /Internal Projects/Kiiro/Kiiro.SiteDefinition/12/TEMPLATE/FEATURES/Kiiro.ProjectPages/Team/EditTeamMember.aspx.cs $
 * 
 * 23    2/08/10 2:28p Camerons
 * 
 * 22    1/11/10 11:51a Camerons
 * 
 * 21    1/06/10 12:39p Camerons
 * 
 * 20    29/10/09 2:58p Camerons
 * 
 * 19    10/26/09 9:40a Adamw
 * 
 * 18    10/23/09 5:53p Adamw
 * Case 348
 * 
 * 17    19/10/09 12:57p Shafia
 * 
 * 16    15/10/09 1:04p Shafia
 * Used ProjectsModel to get current project and enabled the Project
 * Manager Check box when current user is project manager or admin.
 * 
 * 15    30/09/09 4:08p Camerons
 * Update all links that point to UserPages, pass User.SPUserId as the
 * ItemId so that we can safely run GetOrCreateUser
 * 
 * 14    2/09/09 4:50p Camerons
 * 
 * 13    17/08/09 11:07a Camerons
 * Added check-in comments section
 * 
 ************************************************************************/